package com.financing.wap.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

public class HttpClientPostUtil {
	
	
	/**
	 * httpClient请求
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public static String HttpRequest(String urlString,Map<String,String> params) throws Exception{
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = postForm(urlString, params);
		HttpResponse httpResponse = httpClient.execute(httpPost);
		InputStream is = httpResponse.getEntity().getContent();
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		StringBuffer resultSringBuffer =new StringBuffer();
		String result = null;
		while((result = br.readLine())!=null){
			resultSringBuffer.append(result);
		}
		return resultSringBuffer.toString();
	}
	
	/**
	 * 
	* @Title: postForm 
	* @Description: 封装httpPost
	* @param   url 请求地址
	* @param   params  请求参数
	* @param @throws Exception    
	* @return HttpPost   
	* @throws
	 */
	public static HttpPost postForm(String url,Map<String,String> params) throws Exception{
		
		HttpPost httpPost = new HttpPost(url);
		List<NameValuePair> listNameValuePair = new ArrayList<NameValuePair>();
		
		for(String key : params.keySet()){
			listNameValuePair.add(new BasicNameValuePair(key,(String) params.get(key)));
		}
		
		httpPost.setEntity(new UrlEncodedFormEntity(listNameValuePair,HTTP.UTF_8));
		
		return httpPost;
	}
}
